//
//  YYCity.swift
//  YYProject
//
//  Created by 陆文宇 on 2017/8/31.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import RealmSwift

class YYCity: Object {

    @objc dynamic var id = 0
    @objc dynamic var name = ""
    @objc dynamic var parentId = 0
    @objc dynamic var sortNo = 0
    @objc dynamic var code = ""
    @objc dynamic var level = 0
    @objc dynamic var type = 0
    @objc dynamic var category = ""
    
    override class func primaryKey() -> String? {
        return "id"
    }
    
    class func create(_ cities: [Any], isAsync: Bool = true) {
        let closure = {
            let realm = YYRealm.initialize()
            
            realm.beginWrite()
            for city in cities {
                realm.create(self, value: city, update: true)
            }
            try! realm.commitWrite()
        }
        
        if isAsync {
            YYRealm.async(closure)
        } else {
            closure()
        }
    }
    
    class func getOne(name: String?, parentId: Int? = nil) -> YYCity? {
        guard name != nil else {
            return nil
        }
        
        let searchCityParam = name!.replacingOccurrences(of: "市", with: "").replacingOccurrences(of: "县", with: "").replacingOccurrences(of: "区", with: "")
        let predicate = NSPredicate(format: parentId == nil ? "name == %@ OR name == %@ OR name == %@ OR name == %@" : "(name == %@ OR name == %@ OR name == %@ OR name == %@) AND parentId = \(parentId!)", searchCityParam, searchCityParam + "市", searchCityParam + "县", searchCityParam + "区")
        
        let realm = YYRealm.initialize()
        let searchCitys = realm.objects(self).filter(predicate)
        if searchCitys.count > 0 {
            return searchCitys[0]
        }
        
        return nil
    }
    
    class func getDuo(ids: [Int]) -> [YYCity] {
        guard !ids.isEmpty else {
            return []
        }
        
        var idString = ""
        ids.forEach { (id) in
            idString += " OR id = \(id)"
        }
        
        let realm = YYRealm.initialize()
        let items = realm.objects(self).filter(String(idString[idString.index(idString.startIndex, offsetBy: 4)...]))
        return items.map({ (city) -> YYCity in
            return city
        }).sorted(by: { (c1, c2) -> Bool in
            return ids.index(of: c1.id)! < ids.index(of: c2.id)!
        })
    }
    
    class func getOne(id: Int) -> YYCity? {
        guard id > 0 else {
            return nil
        }
        
        let realm = YYRealm.initialize()
        let items = realm.objects(self).filter("id = \(id)")
        if items.count > 0 {
            return items[0]
        } else {
            return nil
        }
    }
    
    class func getSubAll(id: Int) -> [YYCity] {
        let realm = YYRealm.initialize()
        let subCities = realm.objects(self).filter("parentId = \(id)")
        return subCities.map({ (city) -> YYCity in
            return city
        })
    }
    
    class func getAll(types: [Int]) -> [YYCity] {
        guard !types.isEmpty else {
            return []
        }
        
        var typeString = ""
        types.forEach { (type) in
            typeString += " OR type = \(type)"
        }
        
        let realm = YYRealm.initialize()
        let items = realm.objects(self).filter(String(typeString[typeString.index(typeString.startIndex, offsetBy: 4)...])).sorted(byKeyPath: "name")
        return items.map({ (city) -> YYCity in
            return city
        })
    }
    
}
